package com.itbaizhan.shopping_order_customer_api.controller;

/**
 * @author spf
 * @date 2024/1/20
 * @time 21:36
 */

import com.itbaizhan.shopping_common.pojo.Orders;
import com.itbaizhan.shopping_common.pojo.Payment;
import com.itbaizhan.shopping_common.result.BaseResult;
import com.itbaizhan.shopping_common.service.OrdersService;
import com.itbaizhan.shopping_common.service.ZfbPayService;
import org.apache.dubbo.common.json.JSON;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;

/**
 * 支付服务API
 */
@RestController
@RequestMapping("/user/payment")
public class PaymentController {

    @Reference
    private ZfbPayService zfbPayService;
    @Reference
    private OrdersService ordersService;

    @PostMapping("/pcPay")
    public BaseResult<String> pcPay(String orderId){
        Orders orders = ordersService.findById(orderId);
        String codeUrl = zfbPayService.pcPay(orders);
        return BaseResult.ok(codeUrl);
    }

    @PostMapping("/success/notify")
    public BaseResult successNotify(HttpServletRequest request) throws IOException {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("requestParameterMap", request.getParameterMap());
        zfbPayService.checkSign(paramMap);

        String tradeStatus = request.getParameter("trade_status");
        String tradeNo = request.getParameter("out_trade_no");

        if (tradeStatus.equals("TRADE_SUCCESS")){
            // 修改订单状态
            Orders orders = ordersService.findById(tradeNo);
            orders.setStatus(2);
            orders.setPaymentTime(new Date());
            orders.setPaymentType(2);
            ordersService.update(orders);

            // 添加交易记录
            Payment payment = new Payment();
            payment.setOrderId(tradeNo);
            payment.setPayerTotal(orders.getPayment());
            payment.setTradeState(tradeStatus);
            payment.setTransactionId(tradeNo);
            payment.setContent(JSON.json(request.getParameterMap()));

            payment.setCreateTime(new Date());

            zfbPayService.addPayment(payment);
        }
        return BaseResult.ok();
    }

}
